<?php
class system_user_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('system_user_row');		
		$this->setModel('system_user_model', 'system_user');
		$this->setJoinLeftModel('system_passport_model', 'system_user.passport_id = passport.id', 'passport');
		$this->setJoinLeftModel('system_user_group_model', 'system_user_group.id = system_user.group_id', 'system_user_group');
		$this->setModelCols('system_user', array('id', 'passport_id', 'group_id', 'nickname', 'privilege', 'creationtime'));
		$this->setModelCols('passport', array('name', 'identity', 'credential', 'secure', 'email', 'creationip', 'lastupdate', 'lastupip'));
		$this->setModelCols('system_user_group', array('name' => 'group_name', 'privilege' => 'group_privilege', 'is_administrator'));
	}
	
	public function save($row) {
		if($row->getPassportId() == null || intval($row->get('passport_id')) == 0) {
			throw new system_exception("Passport Id can not be empty.");
		}
		if($row->getPrivilege()) {
			$row->setPrivilege(serialize(array()));
		}
		$row->set('passport_id', intval($row->getPassportId()));
		if($row->getId()) {
			$passport = $this->checkPassport($row->getPassportId());
			$row->setPassportId($passport->getId());
			$this->getModel('system_user')->update($row->getModelData('system_user'), array('id = ?' => $row->getId()));			
		} else {
			$passport = $this->checkPassport($row->getPassportId());
			if($this->fetch(array('system_user.passport_id = ?' => $passport->getId()))) {
				throw new system_exception("The Passport Identity(" . $passport->getIdentity() . ") is already existing.");
			}
			$row->setPassportId($passport->getId());
			$date = new system_date();
			$row->setCreationtime($date->get());
			$id = $this->getModel('system_user')->insert($row->getModelData('system_user'));
			$row->setId($id);
		}
		return $row;		
	}
	
	public function checkPassport($passport) {
		$concept = new system_passport_concept();
		if(is_numeric($passport)) {
			$passport = intval($passport);
			if(!($row = $concept->fetch(array('id = ?' => $passport)))) {
				throw new system_exception("The Passport id($passport) is not existing.");
			}
		}
		if(is_string($passport)) {
			$passport = trim($passport);
			if(!($row = $concept->fetch(array('identity = ?' => $passport)))) {
				throw new system_exception("The Passport Identity($passport) is not existing.");
			}
		}
		return $row;
	}

	/**
	 * 密码验证
	 * @param system_user_row $login
	 * @param unknown_type $password
	 */
	public function auth(system_user_row $login, $password) {
		return $login->getCredential() == $password;
	}

}